<?php
class GoodsAction extends AdminAction {

	#列表
	function index() {
		$cate = M('ShopCate')->getField('id,name');
		$path = I('get.path');
		$keyword  = I('get.keyword');

		if($path!=''){
			$map['path'] = array('like', $path.'%');
		}

		if($keyword!=''){
			$map['name'] = array('like', '%'.$keyword.'%');
		}

		$obj = M('Goods');
		$count = $obj->where($map)->count();
		import("@.ORG.Page");
		$page = new Page($count, 10);
		$show = $page->show();
		$list = $obj->where($map)->order('sort asc , id desc')->limit($page->firstRow . ',' . $page->listRows)->select();
		foreach ($list as $key => $value) {
			$list[$key]['album']=M('GoodsImage')->where('goodsID='.$value['id'])->count();
		}

		unset($map);
		$sclass = M('ShopCate')->field("id,name,fid,path")->where($map)->order('path')->select();
		foreach ($sclass as $key => $value) {
			$count = count(explode('-', $value['path'])) - 3;
			$sclass[$key]['count'] = $count;
		}
		$this->assign('sclass', $sclass);
		$this->assign('list', $list);
		$this->assign('page', $show);
		$this->assign('cate', $cate);
		$this->assign('path', $path);
		$this->assign('keyword', $keyword);
		$this->display();

	}

	#添加
	function Add() {
		$cate = M('ShopCate')->field("id,name,fid,path")->where($map)->order('path')->select();	

		foreach ($cate as $key => $value) {
			$count = count(explode('-', $value['path'])) - 3;
			$cate[$key]['count'] = $count;
		}
		$this->assign('cate',$cate);
		$this->display();
	}

	#保存
	function Save() {
		$obj = D('Goods');
		if ($data = $obj->create()) {
			if ($obj->add($data)) {
				$state = 'SUCCESS';
	            $message = '添加成功';
	            $url = U('Goods/index');
			} else {
				$state = '添加失败';
			}
		} else {
			$state = $obj->getError();
		}
		echo $this->echo_json_str($state,$message,$url);
	}

	#编辑
	function Edit() {

		$id = (int) $_GET['id'];
		if (!isset ($id)) {
			$this->error('参数错误');
		}
		$obj = M('Goods');
		$list = $obj->where("id=$id")->find();
		if (!$list) {
			$this->error('信息不存在');
		} else {
			$cate = M('ShopCate')->field("id,name,fid,path")->where($map)->order('path')->select();	
			foreach ($cate as $key => $value) {
				$count = count(explode('-', $value['path'])) - 3;
				$cate[$key]['count'] = $count;
			}
			$this->assign('cate',$cate);
			$this->assign('list', $list);
			$this->display();
		}

	}

	#更新
	function Update() {

		$obj = D('Goods');

		if ($data = $obj->create()) {

			if ($obj->save($data)) {
				$state = 'SUCCESS';
	            $message = '编辑成功';
	            $url = U('Goods/index');
			} else {
				$state = '编辑失败';
			}
		} else {
			$state = $obj->getError();
		}
		echo $this->echo_json_str($state,$message,$url);

	}

	#删除
	function Del() {

		$id=I('post.selectedids');

		if($id==''){
			$state = "您没有选择任何信息！";
		}else{
			foreach ($id as $v) {
				$obj = M('Goods');
				$where['id'] = $v;
				$list = $obj->field('picname')->where($where)->find();
				if ($list['picname']!='') {
					unlink(C('SITE_PATH').$list['picname']);
				}
				$obj->where($where)->delete();

				//删除规格
				$list = M('GoodsSpec')->field('id')->where('goodsid='.$v)->select();	
				foreach ($list as $key => $value) {
					M('GoodsSpecItem')->where('specid='.$value['id'])->delete();
				}
				M('GoodsOption')->where('goodsid='.$v)->delete();
				M('GoodsSpec')->where('goodsid='.$v)->delete();
			}
			$state = 'SUCCESS';
	        $message = '删除成功';
	        $url = U('Goods/index');
		}
		echo $this->echo_json_str($state,$message,$url);
	}


	#相册列表
	public function image(){
		$goodsID = I('get.goodsID');
		$name = M('Goods')->where('id='.$goodsID)->getField('name');
		$this->assign('name',$name);
		$this->assign('goodsID',$goodsID);
		$map['goodsID'] = $goodsID;
		$list = M('GoodsImage')->where($map)->order("sort asc , id desc")->select();
		$this->assign('list',$list);
		$this->display();
	}

	#添加图片
	public function addimg(){
		$goodsID = I('get.goodsID');
		$name = M('Goods')->where('id='.$goodsID)->getField('name');
		$this->assign('name',$name);
		$this->assign('goodsID',$goodsID);
		$this->display();
	}

	public function saveimg(){
		$this->all_add('GoodsImage',U('Goods/image',array('goodsID'=>I('post.goodsID'))));
	}

	#编辑
	public function editimg() {
		$id = (int) $_GET['id'];
		if (!isset ($id)) {
			$this->error('参数错误');
		}
		$obj = M('GoodsImage');

		$list = $obj->where("id=$id")->find();

		if (!$list) {
			$this->error('信息不存在');
		} else {
			$name = M('Goods')->where('id='.$list['goodsID'])->getField('name');
			$this->assign('name', $name);
			$this->assign('list', $list);
			$this->display();
		}

	}

	#更新
	public function updateImg() {
		$this->all_save('GoodsImage',U('Goods/image',array('goodsID'=>I('post.goodsID'))));
	}

	#删除图片
	public function delimg(){
		$id = $_GET['id'];
        if (!isset ($id)) {
            $this->error("您没有选择任何信息！");
        }

        $obj = M('GoodsImage');
		$where['id'] = $id;
		$list = $obj->field('picname')->where($where)->find();
		unlink(C('SITE_PATH').$list['picname']);
		$obj->where($where)->delete();
        redirect ($_SERVER['HTTP_REFERER']);
	}

	//商品规格
	public function pram(){
		$goodsID = I('get.goodsID');
		$goods = M('Goods')->field('name,hasoption')->where('id='.$goodsID)->find();
		if (!$goods) {
			$this->error('商品不存在');
		}
		$this->assign('goods',$goods);
		$this->assign('goodsID',$goodsID);

		$allspecs = M("GoodsSpec")->where("goodsid=".$goodsID."")->order("displayorder asc")->select();
		foreach ($allspecs as &$s) {
			$s['items'] = M("GoodsSpecItem")->where("specid=".$s['id']."")->order("displayorder asc")->select();
        }
        unset($s);
		//处理规格项
        $html = "";
		$options = M("GoodsOption")->where("goodsid=".$goodsID."")->order("id asc")->select();
		//排序好的specs
		$specs = array();
		//找出数据库存储的排列顺序
		if (count($options) > 0) {
			$specitemids = explode("_", $options[0]['specs'] );
            foreach($specitemids as $itemid){
                foreach($allspecs as $ss){
                     $items=  $ss['items'];
                     foreach($items as $it){
                         if($it['id']==$itemid){
                             $specs[] = $ss;
                             break;
                         }
                     }
                }
            }
			$html = '<table style="width:100%;" class="table table-bordered"><thead><tr>';
			$len = count($specs);
            $newlen = 1; //多少种组合
            $h = array(); //显示表格二维数组
            $rowspans = array(); //每个列的rowspan
			for ($i = 0; $i < $len; $i++) {
                //表头
                $html.="<th>" . $specs[$i]['title'] . "</th>";

                //计算多种组合
                $itemlen = count($specs[$i]['items']);
                if ($itemlen <= 0) {
                    $itemlen = 1;
                }
                $newlen*=$itemlen;

                //初始化 二维数组
                $h = array();
                for ($j = 0; $j < $newlen; $j++) {
                    $h[$i][$j] = array();
                }
                //计算rowspan
                $l = count($specs[$i]['items']);
                $rowspans[$i] = 1;
                for ($j = $i + 1; $j < $len; $j++) {
                    $rowspans[$i]*= count($specs[$j]['items']);
                }
            }
			$html .= '<th>库存</th>';
			$html.= '<th>销售价格</th>';
			$html.='<th>市场价格</span></th>';
			$html.='<th>重量(克)</th>';
			$html.='</tr>';
			for($m=0;$m<$len;$m++){
                $k = 0;$kid = 0;$n=0;
                     for($j=0;$j<$newlen;$j++){
                           $rowspan = $rowspans[$m]; //9
                           if( $j % $rowspan==0){
                                $h[$m][$j]=array("html"=> "<td rowspan='".$rowspan."'>".$specs[$m]['items'][$kid]['title']."</td>","id"=>$specs[$m]['items'][$kid]['id']);
                               // $k++; if($k>count($specs[$m]['items'])-1) { $k=0; }
                           }
                           else{
                               $h[$m][$j]=array("html"=> "","id"=>$specs[$m]['items'][$kid]['id']);
                           }
                           $n++;
                           if($n==$rowspan){
                             $kid++; if($kid>count($specs[$m]['items'])-1) { $kid=0; }
                              $n=0;
                           }
                }
            }
			$hh = "";
			for ($i = 0; $i < $newlen; $i++) {
				$hh.="<tr>";
                $ids = array();
                for ($j = 0; $j < $len; $j++) {
                    $hh.=$h[$j][$i]['html'];
                    $ids[] = $h[$j][$i]['id'];
                }
                $ids = implode("_", $ids);              
                $val = array("id" => "","title"=>"", "stock" => "", "costprice" => "", "productprice" => "", "marketprice" => "", "weight" => "");
				if(!empty($options)){					
					 foreach ($options as $o) {
                        if ($ids === $o['specs']) {
                            $val = array("id" => $o['id'],
                                "title"=>$o['title'],
                                "stock" => $o['stock'],
                                "productprice" => $o['productprice'],
                                "marketprice" => $o['marketprice'],
                                "weight" => $o['weight']);
                            break;
                        }
                    }	
				}
				$hh .= '<td>';
                $hh .= '<input name="option_stock_' . $ids . '[]"  type="text" class="form-control option_stock option_stock_' . $ids . '" value="' . $val['stock'] . '"/></td>';
                $hh .= '<input name="option_id_' . $ids . '[]"  type="hidden" class="form-control option_id option_id_' . $ids . '" value="' . $val['id'] . '"/>';
                $hh .= '<input name="option_ids[]"  type="hidden" class="form-control option_ids option_ids_' . $ids . '" value="' . $ids . '"/>';
                $hh .= '<input name="option_title_' . $ids . '[]"  type="hidden" class="form-control option_title option_title_' . $ids . '" value="' . $val['title'] . '"/>';
                $hh .= '</td>';                
                $hh .= '<td><input name="option_productprice_' . $ids . '[]" type="text" class="form-control option_productprice option_productprice_' . $ids . '" " value="' . $val['productprice'] . '" data-rule-required="true"/></td>';
                $hh .= '<td><input name="option_marketprice_' . $ids . '[]" type="text" class="form-control option_marketprice option_marketprice_' . $ids . '" value="' . $val['marketprice'] . '"/></td>';
                $hh .= '<td><input name="option_weight_' . $ids . '[]" type="text" class="form-control option_weight option_weight_' . $ids . '" " value="' . $val['weight'] . '"/></td>';
                $hh .="</tr>";	 
			}
			$html.=$hh;
            $html.="</table>";	
		}
		$this->assign("allspecs",$allspecs);
		
		$this->assign("html",$html);

		$this->display();
	}

	#获取规格html
	public function getspec(){
		$spec = array(
            "id" => $this->GetRandStr(10)
        );
        $item=$this->specitem($spec['id']);
        $this->assign('spec',$spec);
        $this->assign('item',$item);
        $str = $this->fetch();
		echo $str;	
	}


	#添加规格项
	public function specitem($specid){
		$specitem = array(
			"specid" =>$specid,
            "id" => $this->GetRandStr(10),
            "show" => 1
        );	
        $this->assign('specitem',$specitem);
		if($_GET){
			echo $this->fetch('specitem');	
		}else{
			return $this->fetch('specitem');
		}
	}

	public function savepram(){
		$goodsid=I("post.goodsID");
		$spec_ids = I('post.spec_id');
        $spec_titles = I('post.spec_title');
		$hasoption = intval(I('post.hasoption'));
		$len = count($spec_ids);
		$specids = array();
        $spec_items = array();
		for ($k = 0; $k < $len; $k++) {
			 $spec_id = "";
             $get_spec_id = $spec_ids[$k];
             $a = array(
                "goodsid" => $goodsid,
                "displayorder" => $k,
                "title" => $spec_titles[$get_spec_id]
             );
			 $tspec =M("GoodsSpec")->where("id=".$get_spec_id."")->find();
			 if (is_numeric($get_spec_id)&&!empty($get_spec_id)&&!empty($tspec['id'])) {
				M("GoodsSpec")->where("id=".$get_spec_id."")->save($a);
                $spec_id = $get_spec_id;
             } else {
                $spec_id = M("GoodsSpec")->add($a);
             }
			 //子项
             $spec_item_ids = $_POST["spec_item_id_".$get_spec_id];
             $spec_item_titles = $_POST["spec_item_title_".$get_spec_id];
             $spec_item_shows = $_POST["spec_item_show_".$get_spec_id];
             $itemlen = count($spec_item_ids);
             $itemids = array();
			 for ($n = 0; $n < $itemlen; $n++) {
				$item_id = "";
				$get_item_id = $spec_item_ids[$n];
				$d = array(
                   "specid" => $spec_id,
                   "displayorder" => $n,
                   "title" => $spec_item_titles[$n],
                   "show" => $spec_item_shows[$n]
                );
				$tspecitems = M("GoodsSpecItem")->where("id=".$get_item_id."")->find();
				if (is_numeric($get_item_id)&&!empty($get_item_id)&&!empty($tspecitems['id'])) {
					M("GoodsSpecItem")->where("id=".$get_item_id."")->save($d);
                    $item_id = $get_item_id;
                } else {   
                    $item_id = M("GoodsSpecItem")->add($d);
                }
                $itemids[] = $item_id;
				//临时记录，用于保存规格项
                $d['get_id'] = $get_item_id;
                $d['id']= $item_id;
                $spec_items[] = $d;	 
		     }
			  //删除其他的
              if(count($itemids)>0){
				 $map['specid']=$spec_id;
				 $map['id']=array("not in",implode(",", $itemids));
				 M("GoodsSpecItem")->where($map)->delete();  
				 unset($map);
              }else{
				 $map['specid']=$spec_id; 
				 M("GoodsSpecItem")->where($map)->delete();  
				 unset($map);
             }	
			 //更新规格项id
			 $map['id']=$spec_id; 
			 $map['content']=serialize($itemids);
			 M("GoodsSpec")->save($map); 
			 unset($map);
             $specids[] = $spec_id;
		}
		//删除其他的
        if( count($specids)>0){
			$map['goodsid']=$goodsid;
			$map['id']=array("not in",implode(",", $specids));
			M("GoodsSpec")->where($map)->delete($map);
			unset($map); 
        }else{
			$map['goodsid']=$goodsid; 
		    M("GoodsSpec")->where($map)->delete();  
			unset($map);
        }
		//保存规格
		$option_idss = $_POST['option_ids'];
        $option_productprices = $_POST['option_productprice'];
        $option_marketprices = $_POST['option_marketprice'];
        $option_costprices = $_POST['option_costprice'];
        $option_stocks = $_POST['option_stock'];
        $option_weights = $_POST['option_weight'];
        $len = count($option_idss);
        $optionids = array();
		for ($k = 0; $k < $len; $k++) {
			$option_id = "";
            $get_option_id = $_POST['option_id_' . $ids][0];            
            $ids = $option_idss[$k];   
			$idsarr = explode("_",$ids);
            $newids = array();
            foreach($idsarr as $key=>$ida){
                foreach($spec_items as $it){
                    if($it['get_id']==$ida){
                        $newids[] = $it['id'];
                        break;
                    }
                }
            }
            $newids = implode("_",$newids);	
			$a = array(
                 "title" => $_POST['option_title_' . $ids][0],
                 "productprice" => $_POST['option_productprice_' . $ids][0],
                 "costprice" => $_POST['option_costprice_' . $ids][0],
                 "marketprice" => $_POST['option_marketprice_' . $ids][0],
                 "stock" => $_POST['option_stock_' . $ids][0],
                 "weight" => $_POST['option_weight_' . $ids][0],
                 "goodsid" => $goodsid,
                 "specs" => $newids
            );
			$totalstocks+=$a['stock'];
			if (empty($get_option_id)) {
				$option_id = M("GoodsOption")->add($a); 
            } else {
				M("GoodsOption")->where("id=".$get_option_id."")->save($a); 
                $option_id = $get_option_id;
            }
            $optionids[] = (int)($option_id);
		}
		if (count($optionids) > 0) {
			$map['goodsid']=$goodsid;
			$map['id']=array("not in",implode(',', $optionids));
			M("GoodsOption")->where($map)->delete();
			unset($map);
         }else{
			$map['goodsid']=$goodsid;
			M("GoodsOption")->where($map)->delete();
			unset($map);
         }
		unset($map);
		//总库存
        if ($totalstocks > 0) {
			$map['kucun']=$totalstocks;
        }
		$map['id']=$goodsid;
		$map['hasoption']=$hasoption;
		M("Goods")->save($map);
		echo $this->echo_json_str("SUCCESS","操作成功",U('Goods/index'));
	}

}
?>